using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Web.UI;
using System.Web.UI.WebControls;


namespace Hutchinson.CustomField.ItemID
{
    public class HutItemID : SPFieldNumber
    {
        public HutItemID(SPFieldCollection fields, string fieldName)
            : base(fields, fieldName)
        {
        }

        public HutItemID(SPFieldCollection fields, string typeName, string displayName)
            : base(fields, typeName, displayName)
        {
        }

        public override void OnAdded(SPAddFieldOptions op)
        {
            base.OnAdded(op);

            LinkEventHandlers(this.ParentList);

            foreach (SPItem oItem in this.ParentList.Items)
            {
	             oItem[this.InternalName] = oItem["ID"];
                 oItem.Update();
            }

            this.ReadOnlyField = true;
            this.ShowInNewForm = false;
            this.ShowInEditForm = false;
            this.Update();
        }

        private void LinkEventHandlers(SPList liste)
        {
            System.Type myClassType = System.Type.GetType("Hutchinson.CustomField.ItemID.HutItemIDEventHandler");

            SPEventReceiverDefinition SPItemAddedReceiver = GetEventReceiver(liste, SPEventReceiverType.ItemAdded);

            bool doUpdate = false;

            if (SPItemAddedReceiver == null)
            {
                liste.EventReceivers.Add(SPEventReceiverType.ItemAdded, myClassType.Assembly.FullName, myClassType.FullName);

                doUpdate = true;
            }

            if (doUpdate)
                liste.Update();
        }

        private SPEventReceiverDefinition GetEventReceiver(SPList liste, SPEventReceiverType ReceiverType)
        {
            System.Type myClassType = System.Type.GetType("Hutchinson.CustomField.ItemID.HutItemIDEventHandler");

            SPEventReceiverDefinition SPEventReceiver = null;

            foreach (SPEventReceiverDefinition oEvent in liste.EventReceivers)
            {
                if (oEvent.Type == ReceiverType)
                {
                    if (oEvent.Assembly == myClassType.Assembly.FullName && oEvent.Class == myClassType.FullName)
                    {
                        SPEventReceiver = oEvent;
                        break;
                    }
                }
            }

            return SPEventReceiver;
        }
    }

}
